var fs = require('fs');
module.exports = function(app){

app.get('/app/installPackList',function(req, res){
	
	var page = 0;
	if(req.param("page") != undefined){
		page = parseInt(req.param("page"));
	}
	var nextPage = page + 1;cp 
	var previousPage = page - 1;
	var skip = page * 10;
	
	var InstallPackObject = AV.Object.extend("InstallPack");
	var query = new AV.Query(InstallPackObject);
	query.include("installFile");
	query.skip(skip);
	query.limit(10);
	query.find({
		success: function(results) {
			if(results.length > 0){
				res.render('install_pack_list', { InstallPacks : results, next: nextPage, previous: previousPage});
			} else {
				res.render('install_pack_list', { InstallPacks : results, next: 0, previous: previousPage});
			}			
		},
		error: function(error) {
			res.render('error', { message: error.message });	
		}
	});	
		
});

app.post('/app/createInstallPack',function(req, res){
	var InstallPackObject = AV.Object.extend("InstallPack");
	var installPackObject = new InstallPackObject();
	installPackObject.set("versionCode", req.param('versionCode'));
	installPackObject.set("description", req.param('description'));
	installPackObject.set("versionType", req.param('versionType'));
	installPackObject.set("activated", parseInt(req.param('activated')));
	var installFile = req.files.installFile;
	if(installFile.size > 0){		
		fs.readFile(installFile.path, function(err, data){
		  if(err){return res.send("读取文件失败");}
		  var base64Data = data.toString('base64');
		  var avFile = new AV.File(installFile.name, {base64: base64Data});
		  avFile.save().then(function(avFile){
			installPackObject.set("installFile", avFile);
			installPackObject.save(null, {
				success: function(installPackObject) {
					res.render('success', { message: '保存成功！' });
				},
				error: function(installPackObject, error) {
					res.render('error', { message: error.message });
					console.log('signin false: %j', error.code +" : "+ error.message);
				}
			});				
		  });
		});			
	}
});

app.post('/app/changeInstallPackActivated',function(req, res){
	var orderObject = AV.Object.createWithoutData("InstallPack", req.param('installPackId'));
	  orderObject.set("activated", parseInt(req.param('activatedValue')));
	  orderObject.save(null, {
		  success: function(orderObject) {
				res.send('success');				
		  },
		  error: function(orderObject, error) {
			res.send(error.message);
			console.log('signin false: %j', error.code +" : "+ error.message);	
		  }
	});
});

app.post('/app/deleteInstallPack',function(req, res){
	var installPackObject = AV.Object.createWithoutData("InstallPack", req.param('installPackId'));
	installPackObject.destroy({
		  success: function(installPackObject) {
			// The object was deleted from the AVOS Cloud.
			res.send('success');
		  },
		  error: function(installPackObject, error) {
			res.send(error.message);
			console.log('signin false: %j', error.code +" : "+ error.message);	
		  }
	});	
});
}
